package com.yangtu.nearbyshop.admin.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.PageInfo;
import com.yangtu.nearbyshop.admin.dao.MercInf;
import com.yangtu.nearbyshop.admin.util.AdminResponseCode;
import com.yangtu.nearbyshop.core.corg.CorgChannel;
import com.yangtu.nearbyshop.core.util.ResponseUtil;
import com.yangtu.nearbyshop.core.util.bcrypt.BCryptPasswordEncoder;
import com.yangtu.nearbyshop.db.domain.*;
import com.yangtu.nearbyshop.db.service.*;
import com.yangtu.nearbyshop.db.service.itf.INearbyshopBdMercService;
import com.yangtu.nearbyshop.db.util.MercUtil;
import com.yangtu.nearbyshop.db.vo.MercSonCountVo;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.yangtu.nearbyshop.core.corg.Const.*;

@Service

public class AdminMercService {
    private final Log logger = LogFactory.getLog(AdminMercService.class);

    @Autowired
    private NearbyshopMercService mercService;

    @Autowired
    private NearbyshopRegionService regionService;

    @Autowired
    private CorgChannel cnlPayService;

    @Autowired
    private INearbyshopBdMercService bdMercService;

    /**
     * 商户信息列表查询
     *
     * @param mercNm
     * @param mobile
     * @param page
     * @param limit
     * @param sort
     * @param order
     * @return
     */
    public Object list(String mercNm, String mobile,String mercNo,
                       Integer page, Integer limit, String sort, String order) {
        List<NearbyshopMerc> mercList = mercService.querySelective(mercNm, mobile, mercNo,page, limit, sort, order);
        List<Map<String, Object>> mercVoList = new ArrayList<>(mercList.size());
        for (NearbyshopMerc merc: mercList){
            Map<String, Object> mercVo = new HashMap<>();
            mercVo.put("mobile", merc.getMobile());
            mercVo.put("id", merc.getId());
            mercVo.put("latitude", merc.getLatitude());
            mercVo.put("longitude", merc.getLongitude());
            mercVo.put("mercName", merc.getMercName());
            mercVo.put("mercNo", merc.getMercNo());
            mercVo.put("status", merc.getStatus());
            mercVo.put("statusStr", MercUtil.orderStatusText(merc));
            mercVo.put("username", merc.getUsername());
            mercVo.put("realName", merc.getRealName());
            String provNm = regionService.findById(merc.getProvinceId()).getName();
            String cityNm = regionService.findById(merc.getCityId()).getName();
            String areaNm = regionService.findById(merc.getAreaId()).getName();
            String mercAddr = provNm + " " + cityNm + " " + areaNm + " " + merc.getMercAddr();
            mercVo.put("mercAddr", mercAddr);
            mercVo.put("referMerc", merc.getReferMerc());
            MercSonCountVo countVo = mercService.countSon(merc.getId());
            mercVo.put("levelOne",countVo.getLevelOne());
            mercVo.put("levelTwo",countVo.getLevelTwo());
            mercVoList.add(mercVo);
        }
        long total = PageInfo.of(mercList).getTotal();
        Map<String, Object> data = new HashMap<>();
        data.put("total", total);
        data.put("items", mercVoList);

        return ResponseUtil.ok(data);
    }

    /**
     * 商户详情查询
     *
     * @author: ZhangJinChang
     * @Descripition:
     * @param id
     * @Date: 2019/4/23 15:23
    */
    public Object detail(Integer id) {
        NearbyshopMerc merc = mercService.findById(id);
        Map<String, Object> data = new HashMap<>();
        NearbyshopBdMerc bdMerc = bdMercService.getOne(new QueryWrapper<NearbyshopBdMerc>()
            .eq("merc_no",merc.getMercNo()));
        if(bdMerc != null){
            merc.setBdNo(bdMerc.getBdNo());
        }

        data.put("merc", merc);
        return ResponseUtil.ok(data);
    }

    /**
     * 商户添加
     *
     * @author: ZhangJinChang
     * @Descripition:
     * @param mercInf
     * @Date: 2019/4/23 16:57
    */
    public Object create(MercInf mercInf) {
        NearbyshopMerc merc = new NearbyshopMerc();
        String idNo = mercInf.getIdNo();
        merc.setUsername(mercInf.getUsername());
        merc.setAddTime(LocalDateTime.now());
        merc.setAreaId(Integer.parseInt(mercInf.getAreaId()));
        merc.setProvinceId(Integer.parseInt(mercInf.getProvinceId()));
        merc.setCityId(Integer.parseInt(mercInf.getCityId()));
        merc.setCardNo(mercInf.getCardNo());
        merc.setIdNo(idNo);
        merc.setLatitude(mercInf.getLatitude());
        merc.setLongitude(mercInf.getLongitude());
        merc.setMercAddr(mercInf.getMercAddr());
        merc.setMercName(mercInf.getMercName());
        merc.setMobile(mercInf.getMobile());
        merc.setOrgNo(mercInf.getOrgNo());
        merc.setRealName(mercInf.getRealName());
        merc.setBankNm(mercInf.getBankNm());
        String mercNo = "merc" + DateTime.now().toString("yyMMddHHmmss") + RandomUtils.nextInt(1000,6000);
        merc.setMercNo(mercNo);
        if (!StringUtils.isEmpty(mercInf.getReferMerc())) {
            merc.setReferMerc(mercInf.getReferMerc());
        }
        String rawPassword = idNo.substring(idNo.length()-6, idNo.length());
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String encodedPassword = encoder.encode(rawPassword);
        merc.setPassword(encodedPassword);
        merc.setStatus(MercUtil.STATUS_CREATE);


        if (!StringUtils.isEmpty(merc.getOrgNo())) {
            Map<String, String> result = cnlPayService.addFzMerclist(merc.getOrgNo());
            if (!result.get(CMM_PARAM_RETURN_CODE).equals(SUC_RETURN_CODE)) {
                return ResponseUtil.fail(AdminResponseCode.MERC_ORG_NO_INVALID, result.get(CMM_PARAM_RETURN_MSG));
            }
        }
        merc.setStatus(MercUtil.STATUS_NORMAL);
        mercService.add(merc,mercInf.getBdNo());

        return ResponseUtil.ok();
    }

    /**
     * 商户删除
     *
     * @author: ZhangJinChang
     * @Descripition:
     * @param id
     * @Date: 2019/4/23 15:23
     */
    public Object delete(Integer id) {
        mercService.deleteById(id);
        return ResponseUtil.ok();
    }

    /**
     * 商户编辑
     *
     * @author: ZhangJinChang
     * @Descripition:
     * @param mercInf
     * @Date: 2019/4/23 15:23
     */
    public Object update(MercInf mercInf) {
        NearbyshopMerc merc = mercService.findById(Integer.parseInt(mercInf.getId()));
        merc.setMercName(mercInf.getMercName());
        merc.setMobile(mercInf.getMobile());
        merc.setMercAddr(mercInf.getMercAddr());
        merc.setBankNm(mercInf.getBankNm());
        merc.setCardNo(mercInf.getCardNo());
        mercService.updateById(merc,mercInf.getBdNo());
        return ResponseUtil.ok();
    }
}
